package com.kgc.Filter;

import com.alibaba.fastjson.JSONObject;
import com.kgc.util.Constants;
import com.kgc.util.RedisUtil;
import com.kgc.util.Result;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(urlPatterns = {"/user/*"})
public class LoginFilter implements Filter {
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //添加跨域处理
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        //校验是否登录
        String token = request.getHeader("token");
        token = token != null ? token : "";
        long expire = redisUtil.getExpire(token);

        if(expire>0){//有登录
            //重置token有效期
            redisUtil.expire(token,60*30);

            //放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            Result result = new Result(Constants.UN_LOGIN,"用户未登录");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSONObject.toJSONString(result));
        }
    }

    @Override
    public void destroy() {
    }
}
